package com.lzb.musicplayer.audio;

import android.app.Activity;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.SeekBar;
import android.widget.TextView;


import com.lzb.musicplayer.R;
import com.lzb.musicplayer.bean.MusicFile;
import com.lzb.musicplayer.dialog.BottomDialog;
import com.lzb.musicplayer.dialog.SelTimeDialog;
import com.lzb.musicplayer.utils.SpUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;

// AudioPlayerViewInfo.java
public class AudioPlayerViewInfo extends LinearLayout
        implements AudioPlayerManager.PlaybackStateListener {

    // 播放控制组件
    private static ImageView btnPlay, btnPrev, btnNext, ivDl;
    private static TextView currentTime, totalTime;
    private static SeekBar progressBar;

    // 播放管理器引用
    private AudioPlayerManager playerManager;
    private ImageView ivJs, ivXh, ivSj;
    private int count = 0;
    private boolean isOpenCountdown;
    private BottomDialog bottomDlDialog;
    private SelTimeDialog selTimeDialog;


    public AudioPlayerViewInfo(Context context) {
        super(context);
        init(context);
    }

    public AudioPlayerViewInfo(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    private void init(Context context) {
        // 加载布局文件
        inflate(context, R.layout.audio_player_info_layout, this);
        // 初始化播放管理器
        playerManager = AudioPlayerManager.getInstance(context);
        // 绑定视图组件
        bindViews();
        // 设置控件事件
        setupControls();
        btnPlayType();
        playerManager.musicInfo1 = null;
    }

    private void bindViews() {
        btnPlay = findViewById(R.id.btn_play);
        ivDl = findViewById(R.id.ivDl);
        btnPrev = findViewById(R.id.btn_prev);
        btnNext = findViewById(R.id.btn_next);
        progressBar = findViewById(R.id.progress_bar);
        currentTime = findViewById(R.id.current_time);
        totalTime = findViewById(R.id.total_time);
        ivJs = findViewById(R.id.ivJs);
        ivXh = findViewById(R.id.ivXh);
        ivSj = findViewById(R.id.ivSj);
        int xhType = SpUtils.getInstance().getInt("xhType", 0);
        int sjType = SpUtils.getInstance().getInt("sjType", 0);
        if (sjType == 0) {
            ivSj.setImageResource(R.drawable.suiji_off);
//            playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.SHUFFLE);
            if (xhType == 0) {
                ivXh.setImageResource(R.drawable.xunhuan_off);
                playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.NORMAL);
            } else if (xhType == 1) {
                ivXh.setImageResource(R.drawable.xunhuan_on);
                playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.NORMAL);
            } else if (xhType == 2) {
                ivXh.setImageResource(R.drawable.danchuxunhuan_on);
                playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.REPEAT_ONE);
            }
        } else {
            ivSj.setImageResource(R.drawable.suiji_on);
            playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.NORMAL);
        }

        ivJs.setImageResource(isOpenCountdown ? R.drawable.jishi_on : R.drawable.jishi_off);


        if (playerManager != null) {
//            String formattedNumber = String.format("%.2f", playerManager.getSpeed());
//            btn_speed.setText(formattedNumber + "X");
            updateProgressDisplay();
        }
    }

    private void setupControls() {
        // 播放/暂停按钮
        btnPlay.setOnClickListener(v -> playerManager.togglePlayback());

        // 上一首
        btnPrev.setOnClickListener(v -> playerManager.playPrevious());

        // 下一首
        btnNext.setOnClickListener(v -> playerManager.playNext());

        // 进度条拖动监听
        progressBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    playerManager.seekTo(progress * 1000L);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                playerManager.stopProgressUpdates(); // 拖动时暂停自动更新
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                playerManager.startProgressUpdates(); // 结束拖动恢复更新
            }
        });
        ivDl.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDlDialog = new BottomDialog(getContext());
                bottomDlDialog.show();
            }
        });
//        btn_speed.setOnClickListener(new OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                changePlaybackSpeed();
//            }
//        });

        ivJs.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if (selTimeDialog == null) {
                    selTimeDialog = new SelTimeDialog(getContext());
                }
                selTimeDialog.setListener(new SelTimeDialog.Ilistener() {
                    @Override
                    public void clickConfirm() {
                        isOpenCountdown = true;
                        ivJs.setImageResource(R.drawable.jishi_on);
                    }
                });
                selTimeDialog.show();
            }
        });

        ivXh.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int xhType = SpUtils.getInstance().getInt("xhType", 0);
                int sjType = SpUtils.getInstance().getInt("sjType", 0);
                if (sjType == 1) {
                    SpUtils.getInstance().putInt("sjType", 1);
                    ivSj.setImageResource(R.drawable.suiji_off);
                }
                if (xhType == 0) {
                    xhType = 1;
                    playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.NORMAL);
                    ivXh.setImageResource(R.drawable.xunhuan_on);
                } else if (xhType == 1) {
                    xhType = 2;
                    playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.REPEAT_ONE);
                    ivXh.setImageResource(R.drawable.danchuxunhuan_on);
                } else if (xhType == 2) {
                    xhType = 0;
                    playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.REPEAT_ONE);
                    ivXh.setImageResource(R.drawable.xunhuan_off);
                }
                SpUtils.getInstance().putInt("xhType", xhType);

            }
        });

        ivSj.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                int sjType = SpUtils.getInstance().getInt("sjType", 0);
                int xhType = SpUtils.getInstance().getInt("xhType", 0);

                if (xhType == 1) {
                    SpUtils.getInstance().putInt("xhType", 0);
                    ivXh.setImageResource(R.drawable.xunhuan_off);
                }

                if (sjType == 0) {
                    sjType = 1;
                    ivSj.setImageResource(R.drawable.suiji_on);
                    playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.SHUFFLE);
                } else {
                    sjType = 0;
                    ivSj.setImageResource(R.drawable.suiji_off);
                    playerManager.setPlaybackMode(AudioPlayerManager.PlaybackMode.NORMAL);
                }

                SpUtils.getInstance().putInt("sjType", sjType);
            }
        });
    }

    private void changePlaybackSpeed() {

    }

    // region 生命周期管理
    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        // 注册状态监听
        playerManager.addListener(this);

    }

  /*  @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        // 移除状态监听
        playerManager.removeListener(this);
    }*/
    // endregion

    // region 播放控制方法
    public void setPlayList(List<MusicFile> list, int position) {
        playerManager.play(list, position);
    }


    private void updateProgressDisplay() {
        long position = playerManager.getCurrentPosition();
        long duration = playerManager.getDuration();

        progressBar.setMax((int) (duration / 1000));
        progressBar.setProgress((int) (position / 1000));

        currentTime.setText(formatTime(position));
        totalTime.setText(formatTime(duration));

    }

    private String formatTime(long millis) {
        return String.format("%02d:%02d",
                TimeUnit.MILLISECONDS.toMinutes(millis),
                TimeUnit.MILLISECONDS.toSeconds(millis) % 60);
    }

    // endregion
    public int getAudioSessionId() {
        return playerManager.getAudioSessionId();
    }

    @Override
    public void onPlaybackStateChanged(boolean isPlaying) {
        btnPlayType();
    }

    public boolean isPlay() {
        if (playerManager != null) {
            return playerManager.isPlaying();
        }
        return false;

    }

    @Override
    public void onPlaybackStateChanged(int state) {
        updatePlayerState();
        // 控制进度更新
        if (playerManager.isPlaying()) {
            playerManager.startProgressUpdates();
        } else {
            playerManager.stopProgressUpdates();
        }
    }

    @Override
    public void onProgressUpdated(long position, long duration) {
        // 同步其他页面的进度更新（如通知栏）
        progressBar.setProgress((int) (position / 1000));
        currentTime.setText(formatTime(position));
    }

    @Override
    public void onTrackChanged(MusicFile currentTrack) {
        // 更新曲目信息显示

        // 重置进度显示
        progressBar.setProgress(0);
        currentTime.setText("00:00");
        totalTime.setText(formatTime(currentTrack.getDuration()));
    }

    // endregion
    public MusicFile getMusicFile() {
        if (playerManager != null) {
            MusicFile currentTrack = playerManager.getCurrentTrack();
            return currentTrack;
        }
        return null;

    }

    public List<MusicFile> getList() {
        if (playerManager != null) {
            List<MusicFile> list = playerManager.getList();
            return list;
        }
        return null;

    }

    // 辅助方法：更新所有显示状态
    private void updatePlayerState() {
        btnPlayType();
        updateProgressDisplay();
    }

    private void btnPlayType() {
        btnPlay.setBackgroundResource(
                playerManager.isPlaying() ? R.drawable.stop2 : R.drawable.start
        );

    }

    public void setSeed() {
        changePlaybackSpeed();
    }
}